﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using STS.Schema.Interfaces;
using STS.Schema.Collections;
using STS.Schema.Enums;
using STS.Schema.Base;
using STS.Interfaces;

namespace STS.Schema.MSSql
{
    public class MSSqlTable : SqlObjectBase, ITable
    {
        private Lazy<ISqlObjectCollection> _columnList;
        private Lazy<ISqlObjectCollection> _foreignKeyList;
        private Lazy<ISqlObjectCollection> _triggerList;

        public override SqlObjectType ObjectType
        {
            get { return SqlObjectType.UserTable; }
        }

        [SqlQueryProperty("id")]
        public override int ObjectID
        {
            get;
            internal set;
        }

        [SqlQueryProperty("name")]
        public override string Name
        {
            get;
            internal set;
        }

        public ISqlObjectCollection ColumnList { get { return _columnList.Value; } }
        public ISqlObjectCollection ForeignKeyList { get { return _foreignKeyList.Value; } }
        public ISqlObjectCollection TriggerList { get { return _triggerList.Value; } }

        public MSSqlTable(ISchemaFactory schemaFactory, IDatabase database)
            : base(schemaFactory, database)
        {
            InitLazyObjects();
        }

        public MSSqlTable()
            : this(null, null)
        {

        }

        private void InitLazyObjects()
        {
            _columnList = new Lazy<ISqlObjectCollection>(() =>
            {
                return GetChildren<MSSqlColumn>();
            });
            _foreignKeyList = new Lazy<ISqlObjectCollection>(() =>
            {
                return GetChildren<MSSqlForeignKey>();
            });
            _triggerList = new Lazy<ISqlObjectCollection>(() =>
            {
                return GetChildren<MSSqlTrigger>();
            });
        }

        public override ISqlObjectCollection GetChildren<TChild>()
        {
            return base.Factory.GetObjectList<TChild>(this, null, base.Database);
        }

        public override void Refresh()
        {
            base.Refresh();
            base.Factory.ClearObjectList<MSSqlColumn>(base.Database);
            base.Factory.ClearObjectList<MSSqlForeignKey>();
            InitLazyObjects();
        }
    }
}
